/**
 * Create by CaoWenjian
 *
 * @copyRight: 2018
 **/
package com.bjboot.caocao.system.controller;

import com.bjboot.caocao.common.config.Constant;
import com.bjboot.caocao.common.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *@Description 对于错误信息的处理控制器
 *@Author 操文健
 *@Date 2018-09-06 下午2:13
 *@Version 1.0
 **/
@RestController
public class SysErrorController implements ErrorController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private static final String ERROR_PATH = "/error";

    // 对错误信息界面的返回处理
    @RequestMapping( value = {ERROR_PATH}, produces = {"text/html"} )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        int code = response.getStatus();
        if (Constant.ERROR_CODE_404 == code) {
            return new ModelAndView("error/404");
        } else if (Constant.ERROR_CODE_403 == code) {
            return new ModelAndView("error/403");
        } else if (Constant.ERROR_CODE_401 == code) {
            // 未登陆， 跳转到登陆界面
            return new ModelAndView("login");
        } else {
            return new ModelAndView("error/500");
        }

    }

    // 对非界面错误对返回处理
    @RequestMapping(value = ERROR_PATH)
    public Result handleError(HttpServletRequest request, HttpServletResponse response) {
        response.setStatus(Constant.SUCCESS_CODE_200);
        int code = response.getStatus();
        if (Constant.ERROR_CODE_404 == code) {
            return Result.error(Constant.ERROR_CODE_404, Constant.ERROR_CODE_404_NAME);
        } else if (Constant.ERROR_CODE_403 == code) {
            return Result.error(Constant.ERROR_CODE_403, Constant.ERROR_CODE_403_NAME);
        } else if (Constant.ERROR_CODE_401 == code) {
            return Result.error(Constant.ERROR_CODE_401, Constant.ERROR_CODE_401_NAME);
        } else {
            return Result.error(Constant.ERROR_CODE_500, Constant.ERROR_CODE_500_NAME);
        }
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
